package main.database;

import java.util.HashMap;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class DatabaseTuner 
{
	private String confFile;
	private String driver;
	private String cs;
	
	
	private DatabaseTuner(String confFile, String driver, String cs)
	{
		this.confFile = confFile;
		this.driver = driver;
		this.cs = cs;
	}
	
	public String getDriver()
	{
		return driver;
	}
	
	public String getCs()
	{
		return cs;
	}
	
	public static DatabaseTuner load(String fileName) throws Exception
	{
		Document config = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(fileName);
		NodeList connection = config.getDocumentElement().getElementsByTagName("connection");
		if (connection.getLength() > 0)
		{
			StringBuilder params = new StringBuilder();
			Element element = (Element) connection.item(0);
			if (element.hasAttribute("driver") && element.hasAttribute("cs"))
			{	
				NodeList properties = config.getElementsByTagName("property");
				for (int i = 0; i < properties.getLength(); i++)
				{
					Element property = (Element)properties.item(i);
					if (property.hasAttribute("name") && property.hasAttribute("value"))
					{
						params = (params.length() > 0) ? params.append('&') : params.append('?');
						params.append(property.getAttribute("name")).append('=').append(property.getAttribute("value"));
					}
				}
				DatabaseTuner tuner = new DatabaseTuner(fileName, element.getAttribute("driver"), element.getAttribute("cs") + params.toString());
				//tuner.loadQueries();
				return tuner;
			}
			else
			{
				throw new Exception("Config file has incorrect connection tune.");
			}
		}
		else
		{
			throw new Exception("Config file doesn't have connection tune.");
		}
	}
	
	public HashMap<String, String> loadQueries() throws Exception
	{
		HashMap<String, String> queries = new HashMap<String, String>();
		Document config = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(confFile);
		NodeList queryNodes = config.getDocumentElement().getElementsByTagName("query");
		for (int i = 0; i < queryNodes.getLength(); i++)
		{
			Element element = (Element)queryNodes.item(i);
			if (element.hasAttribute("name"))
			{
				Node sql = element.getFirstChild();
				if (sql instanceof Text)
				{
					queries.put(element.getAttribute("name"), sql.getTextContent());
				}
			}
		}
		return queries;
	}
}
